package com.jar.exercise.多线程.threadlocal;


import java.util.Random;

/**
 * <div  style="border:2px solid none;margin:20px;padding:15px;font-size:24px;text-align:center;color:aqua;">
 *
 *
 *
 *  </div>
 *
 * @author zhangshun
 * @date 2021/4/6 12:49
 */
public class ThreadLocalTest02 {


    public static void main(String[] args) {

        Cale.init();

        sleep();

        Cale.print("one");
        sleep();

        Cale.print("two");
        sleep();

        Cale.print("three");
        sleep();

        Cale.print("four");
        sleep();

        Cale.print("five");
        sleep();

        Cale.print("six");
        Cale.shutdown();

    }




    private static void sleep(){
        try {
            final int i = new Random().nextInt(1000);
            System.out.println("Random : " + i);
            Thread.sleep(i);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    /**
     *  cale the time to process.
     */
    static class Cale{

        // 当前服务器时间戳

        private static final ThreadLocal<Long> THREAD_LOCAL = ThreadLocal.withInitial(System::currentTimeMillis);



        public static void init(){
            THREAD_LOCAL.get();
        }

        public static void print(String name){
            // 当前服务器时间戳
            final long now = System.currentTimeMillis();
            System.out.println(name + ":" + (now - THREAD_LOCAL.get()) +" ms");
            THREAD_LOCAL.set(now);
        }

        public static void shutdown(){
            THREAD_LOCAL.remove();
        }

    }


}
